package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import org.apache.ibatis.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * @author 黄军艳
 * @version 1.0
 * @date 2024/12/19  14:19
 */
@Controller
@RequestMapping("/main/supplier")
public class SupplierController extends BaseController {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SupplierController.class);
    @Autowired
    private SupplierService supplierService;

    //分页查询并附带模糊条件
    @RequestMapping("/page")
    public String page(Model model, Supplier condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Page<Supplier> page=null;
        try {
            page=supplierService.findPage(condition, pageNo, pageSize);
            model.addAttribute("pageInfo", page);
            model.addAttribute("condition", condition);
        }catch (Exception e) {
            LOGGER.error("SupplierController 中的 page 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "supplier/page";
    }

    //点击添加按钮跳转到添加页面
    @GetMapping("/save")
    public String tosave(){
        return "supplier/save";
    }
    //执行添加/修改数据操作
    @PostMapping("/save")
    public String dosave(Supplier supplier,
                         @RequestParam("bizPic") MultipartFile bizPic){
        // 设置保存路径
        String uploadPath="/statics/upload/";
        String rootPath = request().getServletContext()
                .getRealPath(uploadPath);
        try {
            //营业执照
            if(bizPic!=null && !bizPic.isEmpty()) {
                //1. 文件重命名：文件名的格式：随机数.文件后缀
                String fileName = bizPic.getOriginalFilename();
                // 获得上传文件的扩展名
                String extension = StringUtils.getFilenameExtension(fileName);
                // 生成新的文件名
                String uploadFileName = UUID.randomUUID() + "." + extension;
                //2.文件存储
                File file = new File(rootPath, uploadFileName);
                // 父目录不存在是无法保存的
                if (!file.getParentFile().exists()) {
                    // 创建父目录
                    file.getParentFile().mkdirs();
                }
                //保存文件
                bizPic.transferTo(file);
                //3.属性赋值
                supplier.setBizPicPath(uploadPath + uploadFileName);
            }
            //通过父类的 session 方法获取登录用户
            SysUser sysUser=session(Constants.SESSION_USER);
            boolean ok = false;
            if (supplier.getId()==null){
                supplier.setCreatedUserId(sysUser.getId());
                supplier.setCreatedTime(new Date());
                ok=supplierService.insert(supplier);
            }else {
                supplier.setUpdatedTime(new Date());
                supplier.setUpdatedUserId(sysUser.getId());
                ok=supplierService.update(supplier);
            }
            if (ok) {
                // 保存成功，跳回列表页面
                return redirect("/main/supplier/page");
            }
        }catch (Exception e) {
            LOGGER.error("SupplierController 中的 doSave 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    /**
     * 详情页
     */
    @GetMapping("/view/{id}")
    public String view(Model model,@PathVariable("id") Long id){
        Supplier supplier=null;
        supplier=supplierService.findById(id);
        model.addAttribute("supplier", supplier);
        return "supplier/view";
    }

    /**
     * 查询用户信息并跳转修改页（共用 save.jsp)
     */
    @GetMapping("/edit")
    public String toEdit(Model model,@RequestParam("id") Long id){
        Supplier supplier=null;
        supplier=supplierService.findById(id);
        model.addAttribute("supplier", supplier);
        return "supplier/save";
    }

    @GetMapping("/supCodeExist")
    @ResponseBody
    public Object supCodeExist(@RequestParam("supCode") String supCode){
        Supplier supplier=null;
        Map<String,Object> map=new HashMap<>();
        try {
            supplier=supplierService.selectSupCode(supCode);
            if (supplier!=null){
                map.put("exist",1);
            }else {
                map.put("exist",0);
            }
        }catch (Exception e) {
            LOGGER.error("SupplierController 中的 supCodeExist 方法执行发生错误。 ", e);
            map.put("exist",-1);
            map.put("error","服务器繁忙，请稍后再试！");
        }
        return map;
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Integer id){
        Map<String,Object> map=new HashMap<>();
        try {
            boolean ok=supplierService.delete(id);
            if (ok){
                map.put("code",200);
            }else {
                map.put("code",500);
            }
        }catch (Exception e) {
            LOGGER.error("SupplierController 中的 del 方法执行发生错误。 ", e);
            map.put("exist",-1);
            map.put("error","删除失败");
        }
        return map;
    }
}
